package com.klondike.common.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class MutuxImpl extends ReentrantLock implements Mutux {
    private static final long serialVersionUID = 1L;

    private volatile long timestamp;

    public MutuxImpl() {
        super(true);
    }

    @Override
    public long wasLockedOn() {
        return timestamp;
    }

    @Override
    public boolean tryLock() {
        return updateLockedOn(super.tryLock());
    }

    @Override
    public void lock() {
        super.lock();
        updateLockedOn(true);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        super.lockInterruptibly();
        updateLockedOn(true);
    }

    @Override
    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
        return updateLockedOn(super.tryLock(timeout, unit));
    }

    private boolean updateLockedOn(boolean locked) {
        if (locked) {
            timestamp = System.currentTimeMillis();
        }
        
        return locked;
    }
}
